<template>
  <!-- 列表 -->
  <ContentWrap>
    <el-button
      type="primary"
      plain
      @click="openForm('create')"
      v-hasPermi="['mes:base-work-shop:create']"
    >
      <Icon icon="ep:plus" class="mr-5px"/>
      新增
    </el-button>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!--      <el-table-column label="机台信息ID" align="center" prop="id" />-->
      <!--       <el-table-column label="区域代码" align="center" prop="machineAreaCode" />-->
      <!--      <el-table-column label="机台区域" align="center" prop="machineArea" />-->
      <el-table-column fixed label="机台名称" align="center" prop="machineName"/>
      <el-table-column label="机台编码" align="center" prop="machineCode"/>
      <el-table-column label="机台参数" align="center" prop="machineProperty"/>
      <el-table-column label="机台品牌" align="center" prop="machineBrand"/>
      <el-table-column label="机台状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_MACHINE_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否离线" align="center" prop="offline">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_DEVICE_OFFLINE" :value="scope.row.offline+''"/>
        </template>
      </el-table-column>
      <el-table-column label="PLC编号" align="center" prop="machinePlcId"/>
      <el-table-column label="项目编号" align="center" prop="projectId"/>
      <el-table-column label="区域编号" align="center" prop="regionId"/>

      <el-table-column label="电子秤数量" align="center" prop="weightNum" min-width="100px"/>
      <el-table-column label="人力排班" align="center" prop="isScheduling">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isScheduling"/>
        </template>
      </el-table-column>
      <el-table-column label="是否是机台" align="center" prop="isMachine" min-width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isMachine"/>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNo"/>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="150px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['mes:base-work-shop:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['mes:base-work-shop:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 表单弹窗：添加/修改 -->
  <BaseMachineInfoForm ref="formRef" @success="getList"/>

</template>
<script setup lang="ts">
import {DICT_TYPE} from '@/utils/dict'
import {BaseMachineAreaVO, BaseWorkShopApi} from '@/api/mes/baseworkshop'
import BaseMachineInfoForm from './BaseMachineInfoForm.vue'
import bus from "@/utils/eventBus"
import {clone} from "@/utils/tools";
import {dateFormatter} from "@/utils/formatTime";


const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗


const loading = ref(false) // 列表的加载中
let list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
let queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  workShopId: undefined as unknown,
  machineAreaId: undefined as unknown
})
const queryParamsModel = reactive({
  pageNo: 1,
  pageSize: 10,
  workShopId: undefined as unknown,
  machineAreaId: undefined as unknown
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BaseWorkShopApi.getBaseMachineInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  console.log("ReceiveData:", receiveData.value)
  try {
    let data = receiveData.value as BaseMachineAreaVO
    queryParams.pageNo = 1
    queryParams.machineAreaId = data.id
    queryParams.workShopId = data.workShopId
    getList()
  } catch (e) {
    list = []
  }
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = async (type: string, id?: number) => {
  console.log("Re:", receiveData.value)
  let workShopList = await BaseWorkShopApi.getSimpleWorkShopList()
  if (workShopList.length === 0) {
    message.error('请添加车间信息！')
    return
  }
  let machineAreaList = await BaseWorkShopApi.getSimpleMachineAreaList()
  if (machineAreaList.length === 0) {
    message.error('请添加区域信息！')
    return
  }
  let data = receiveData.value as BaseMachineAreaVO
  // if (!data.id) {
  //   message.error('请选择一个区域信息')
  //   return
  // }
  formRef.value.open(type, id, data, machineAreaList, workShopList)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BaseWorkShopApi.deleteBaseMachineInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}
const reset = async (workShopId: string) => {
  queryParams = clone(queryParamsModel)
  queryParams.workShopId = workShopId
  handleQuery()
}

defineExpose({reset})

let receiveData = ref({})
onMounted(() => {
  // 订阅事件
  const off = bus.on('currentRow', (data: BaseMachineAreaVO) => {
    receiveData.value = data as BaseMachineAreaVO
    console.log('Received data from brother:', receiveData)
    // 在这里可以更新组件B的状态或者执行其他业务逻辑

    handleQuery()
  })

  // 当组件卸载时，取消事件订阅以避免内存泄漏
  onUnmounted(() => {
    off()
  })
})

</script>
